package cn.itsource.product.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.product.domain.Product;
import cn.itsource.product.domain.ProductDetail;
import cn.itsource.product.mapper.ProductDetailMapper;
import cn.itsource.product.mapper.ProductMapper;
import cn.itsource.product.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProductServiceImpl extends BaseServiceImpl<Product>
        implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ProductDetailMapper productDetailMapper;

    @Override
    public void del(Long id) {
        //除了删除自己还要删除详情
        productMapper.remove(id);
        //通过ProductId删除ProductDetail
        productDetailMapper.removeByProductId(id);
    }

    @Override
    public void add(Product product) {
        productMapper.save(product);
        ProductDetail detail = product.getDetail();
        if (detail!=null){
            detail.setProduct_id(product.getId());
            productDetailMapper.save(detail);
        }
    }

    @Override
    public void update(Product product) {
        productMapper.update(product);
        //是否有详情
        ProductDetail detail = product.getDetail();
        if (detail!=null){
            if (detail.getId()!=null){
                //有详情
                productDetailMapper.update(detail);
            }else{
                productDetailMapper.save(detail);
            }
        }
    }

    @Override
    public ProductDetail getDetailByProductId(Long productId) {
        return productDetailMapper.loadByProductId(productId);
    }

    //flag标识 1上架 0下架
    @Override
    public void onsaleOrOffsale(List<Long> ids, int flag) {

        if (flag==1){
            //上架：上架服务们ids（批量修改），上架时间
            Map<String,Object> params = new HashMap<>();
            params.put("ids",ids);
            params.put("onsaletime",new Date());
            productMapper.onsale(params);
        }else{
            //下架
            Map<String,Object> params = new HashMap<>();
            params.put("ids",ids);
            params.put("offsaletime",new Date());
            productMapper.offsale(params);
        }
    }
}
